﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using BLL;
using POS.Framework;
using Model.Bill;
using DevExpress.Utils;
using BLL.Enums;
using DevExpress.Xpo;
using Model;
using DevExpress.Data.Filtering;

namespace POS.ModForm.Sale
{
    public partial class frmReturnSale : DevExpress.XtraEditors.XtraForm
    {
        ProductBLL productBLL = new ProductBLL();
        OrderBLL orderBLL = new OrderBLL();
        OrderDetailBLL orderDetailBLL = new OrderDetailBLL();
        MyGridChedkMarksSelectionHelper ChedkSelect { get; set; }
        TB_Order order = null;
        string orderRemark = string.Empty;
        public frmReturnSale()
        {
            InitializeComponent();
        }

        private void frmReturnSale_Load(object sender, EventArgs e)
        {
            using (WaitDialogForm wdf = new WaitDialogForm(MsgBox.WaitLoading))
            {
                this._SellDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                this.gridView.CustomDrawRowIndicator += new DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventHandler(SpecialGridView.DrawRowIndicator);
                this.ChedkSelect = new MyGridChedkMarksSelectionHelper(this.gridView);
                SetButtonClickEvent();
                this.repositoryItemLookUpEditProductType.DataSource = EnumManage.GetDictionaryEntry(typeof(ProductType));
                this.repositoryItemLookUpEditUnit.DataSource = EnumManage.GetDictionaryEntry(BaseEnum.Unit);
                wdf.Close();
            }
        }
        void SetButtonClickEvent()
        {
            addItemSaleUC.AddDetail.Click += new EventHandler(AddDetail);
            addItemSaleUC.DelDetail.Click += new EventHandler(btnDelete_Click);
            addItemSaleUC.SellPriceControl.KeyPress += new KeyPressEventHandler(SellPriceControl_KeyPress);
            addItemSaleUC.InitBindWarehouse();
            addItemSaleUC.LookUpProduct.Properties.DataSource = productBLL.GetProducts();
            addItemSaleUC.LookUpProduct.Select();
        }
        void AddDetail(object sender, EventArgs e)
        {
            Session s = DatabaseSchema.Session;
            try
            {
                s.BeginTransaction();
                if (order == null)
                {
                    order = new TB_Order(s);
                    order.OrderID = PlanIDBLL.GetPlanID(s,"XS", this._SellDate.Text.Trim());
                    order.BillCode = order.OrderID;
                    order.StoreID = s.FindObject<B_Store>(CriteriaOperator.Parse("StoreCode=?", MemberInfo.StoreCode));
                    order.SellDate = Convert.ToDateTime(this._SellDate.Text);
                    order.Remark = orderRemark;
                    order.TypeID = (int)OrderType.ReturnGood;
                    order.Save();
                }
                orderDetailBLL.Add(order, addItemSaleUC.WarehouseID, addItemSaleUC.ProductID, ProductType.Nothing, addItemSaleUC.Quantity, addItemSaleUC.SellPrice);
                s.CommitTransaction();
            }
            catch (Exception ex)
            {
                s.RollbackTransaction();
                MsgBox.ShowWarning(ex.Message);
                return;
            }
            order.OrderDetails.Reload();
            this.gridControl.DataSource = order.OrderDetails;
            ShowOrderUI();
            MsgBox.ShowTips("添加退货单明细成功！");
            addItemSaleUC.ControlResetText();
        }
        void btnDelete_Click(object sender, EventArgs e)
        {
            if (this.ChedkSelect.SelectedCount <= 0)
            {
                MsgBox.ShowWarning("请选中要删除的货品!");
                return;
            }
            try
            {
                foreach (TB_OrderDetail od in this.ChedkSelect._Selection)
                {
                    if (od != null)
                        od.Delete();
                }
                orderBLL.CalcOrderAmount(order);
                MsgBox.ShowTips("删除退货单明细成功！");
            }
            catch (Exception ex)
            {
                MsgBox.ShowWarning(ex.Message);
                return;
            }
            order.OrderDetails.Reload();
            this.gridControl.DataSource = order.OrderDetails;
            ShowOrderUI();
        }
        void SellPriceControl_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (addItemSaleUC.SellPriceControl.Properties.Mask.MaskType != DevExpress.XtraEditors.Mask.MaskType.Numeric)
            {
                addItemSaleUC.SellPriceControl.Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric;
                addItemSaleUC.SellPriceControl.Properties.Mask.EditMask = "f2"; ;
                addItemSaleUC.SellPriceControl.Properties.Mask.UseMaskAsDisplayFormat = true;
            }
            if (e.KeyChar == 13)
                AddDetail(sender, e);
        }
        void ShowOrderUI()
        {
            if (order == null)
            {
                this._SellDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                this._CopeAmount.Text = "0.00￥";
                this._ActualAmount.Text = "0.00￥";
                this.groupControl1.Text = "退货单基本信息";
            }
            else
            {
                this._SellDate.Text = order.SellDate.ToString("yyyy-MM-dd");
                this._CopeAmount.Text = order.CopeAmount.ToString("f2") + "￥";
                this._ActualAmount.Text = "0.00￥";
                this.groupControl1.Text = string.Format("退货单号：{0}  状态：{1}", order.BillCode, EnumManage.GetBillStatus(typeof(OrderStatus), order.StatusID));
            }
        }
        private void btnPayMent_Click(object sender, EventArgs e)
        {
            if (order == null || order.OrderDetails.Count == 0)
            {
                MsgBox.ShowWarning("请添加要退货的货品！");
                return;
            }
            using (frmPayMent fpm = new frmPayMent(order))
            {
                if (fpm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    MsgBox.ShowTips("门市退货成功！");
                    ShowOrderUI();
                    orderRemark = string.Empty;
                    order = null;
                    this.gridControl.DataSource = null;
                }
            }
        }

        private void btnMakeUp_Click(object sender, EventArgs e)
        {
            if (order != null)
            {
                if (MsgBox.ShowYesNoCancelAndTips("是否要清除当前单据的信息！") == System.Windows.Forms.DialogResult.Yes)
                {
                    order = null;
                    this.gridControl.DataSource = null;
                    ShowOrderUI();
                }
                else
                {
                    return;
                }
            }
            using (frmMend fpm = new frmMend())
            {
                if (fpm.ShowDialog() == System.Windows.Forms.DialogResult.Yes)
                {
                    this._SellDate.Text = fpm.SellDate;
                    this.orderRemark = fpm.Remark;
                }
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            if (order != null && order.OrderDetails.Count > 0)
            {
                if (MsgBox.ShowYesNoAndWarning("门市退货已生成，是否要取消订单!") == System.Windows.Forms.DialogResult.Yes)
                {
                    this.Close();
                }
            }
            else
            {
                this.Close();
            }
        }
    }
}